package _5thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description:
 * @Author wangzhen
 * @Date 2022-06-21 19:11
 **/
public class ReentrantReadWriteLockTest {

    static ReadWriteLock lock = new ReentrantReadWriteLock();
    static Lock readLock = lock.readLock();
    static Lock writeLock = lock.writeLock();

    static int value = 0;

    public static int getValue() {
        return value;
    }

    public static void setValue(int value) {
        ReentrantReadWriteLockTest.value = value;
    }

    public static void main(String[] args) {

        new Thread(() -> {


            try {
                writeLock.lock();


                System.out.println("准备写入");
                value++;
                setValue(value);
                System.out.println("写入完成");

                readLock.lock();
                System.out.println("准备读取");
                int value = getValue();
                System.out.println("读取完成");
                writeLock.unlock();

                //剩下的业务继续
            } finally {
                readLock.unlock();
            }


        }).start();

    }


}
